#! /usr/bin/env python
#coding:utf-8
import os
import time
import upyun
import hashlib
import urllib2
from lovewith.settings import FILE_UPLOAD_PATH


class Upyun:
    def __init__(self, type):
        up_backet_name = 'mt-share'
        up_username = 'cosa'
        up_password = 'cosa19851129'

        #文件保存路径
        if type == 'share':
            self.save_path = 'share/%s' % time.strftime('%Y/%m/%d/', time.localtime(time.time()))
        if type == 'cate':
            self.save_path = 'cate/%s' % time.strftime('%Y/%m/%d/', time.localtime(time.time()))
        if type == 'avatar':
            self.save_path = 'avatar/%s' % time.strftime('%Y/%m/%d/', time.localtime(time.time()))
        if type == 'promote':
            self.save_path = 'promote/%s' % time.strftime('%Y/%m/%d/', time.localtime(time.time()))
        if type == 'card':
            self.save_path = 'card/%s' % time.strftime('%Y/%m/%d/', time.localtime(time.time()))
        if type == 'subanner':
            self.save_path = 'subanner/%s' % time.strftime('%Y/%m/%d/', time.localtime(time.time()))

        self.local_upload_path = FILE_UPLOAD_PATH
        #域名
        self.domain = 'http://i1.etosun.com/'
        self.up = upyun.UpYun(up_backet_name, up_username, up_password, timeout=30, endpoint=upyun.ED_AUTO)

    #获取文件完整保存路径
    def get_save_path(self, source_path):
        #扩展名
        if source_path.find('http') < 0:
            ext_name = os.path.splitext(source_path)[1]
        else:
            #文件扩展名
            ext_name = 'jpg'

        #文件名
        new_file_name = hashlib.new('md5', source_path).hexdigest()
        #保存路径
        new_save_path = '%s%s%s' % (self.save_path, new_file_name, ext_name)

        return new_save_path

    #保存头像
    def save_avatar(self, avatar_url):
        res = {}
        save_path = self.get_save_path(avatar_url)

        if avatar_url.find('http') > -1:
            http = urllib2.urlopen(avatar_url)
            res = self.up.put(save_path, http.read())
        else:
            full_avatar_path = '%s%s' % (self.local_upload_path, avatar_url)
            #判断文件是否存在
            if os.path.exists(full_avatar_path):
                with open(full_avatar_path, 'rb') as f:
                    res = self.up.put(save_path, f)

        if res and res.get('width'):
            return '%s%s' % (self.domain, save_path)
        else:
            return None

    #保存原图
    def save_source_file(self, source_path):
        res = {}
        #设置不允许直接对外提供访问
        headers = {'content-secret': '@$#%$^%&^*'}
        #判断文件是否存在
        if os.path.exists(source_path):
            save_path = self.get_save_path(source_path)
            with open(source_path, 'rb') as f:
                res = self.up.put(save_path, f, headers=headers)

        if res.get('width'):
            return '%s%s' % (self.domain, save_path)
        else:
            return None

    #保存图片
    def save_image(self, source_path):
        res = {}
        #判断文件是否存在
        if os.path.exists(source_path):
            save_path = self.get_save_path(source_path)
            with open(source_path, 'rb') as f:
                res = self.up.put(save_path, f)

        if res.get('width'):
            return '%s%s' % (self.domain, save_path)
        else:
            return None

    #删除图片
    def delete(self, full_path):
        try:
            file_path = full_path.replace(self.domain, '/')
            self.up.delete(file_path)
        except StandardError, api_error:
            pass

    #上传图片
    def upload(self, attach):
        #if hasattr(attach, "name") and not attach.name == "":
        #    save_path = self.get_save_path(attach.name)
        #    res = self.up.put(save_path, attach.read())
        #    if res.get('width'):
        #        return '%s%s' % (self.domain, save_path)

        return self.save_path
